<?php
class Agitum_Model_Route extends Agitum_Model_Object 
{
	protected $_t_class = 'Agitum_Model_DbTable_Route';
	
	const ZEND_CONTROLLER_ROUTER_ROUTE_STATIC = 1;
	const ZEND_CONTROLLER_ROUTER_ROUTE = 2;
	const ZEND_CONTROLLER_ROUTER_ROUTE_REGEXP = 3;
	
	public function getRouteList() 
	{
		$db = Zend_Registry::get('Zend_Db');
		$select = $db->select();
		
		$rows = $this->fetchAll();
	    
		$ids = array();
		$routes = array();
		
		foreach ($rows as $i => $row) {
		    $route = null;
		    $defs = $this->_toTextArray ( $row['defvars'] );
			$defs ['module'] = $row ['module'];
			$defs ['controller'] = $row ['controller'];
			$defs ['action'] = $row ['action'];
			$_defs = var_export($defs, true);
			$subject = $row['subject'];
		    switch($row['type']) {
				case Agitum_Model_Route::ZEND_CONTROLLER_ROUTER_ROUTE :
				    $routes [$row['name']] = new Zend_Controller_Router_Route ( $row['subject'], $defs );
//					echo "routes[{$row['name']}] = new Zend_Controller_Router_Route ( {$row['subject']}, $_defs );<br/>";
					break;
			    case Agitum_Model_Route::ZEND_CONTROLLER_ROUTER_ROUTE_STATIC :
			    	$routes [$row['name']] = new Zend_Controller_Router_Route_Static ( $row['subject'], $defs );
//				    echo "routes[{$row['name']}] = new Zend_Controller_Router_Route_Static ( {$row['subject']}, $_defs );<br/>";
				    break;
			    case Agitum_Model_Route::ZEND_CONTROLLER_ROUTER_ROUTE_REGEXP :
				    $_map = $this->_toTextArray ( $row ['map'] );
					$routes [$row['name']] = new Zend_Controller_Router_Route_Regex ( $row['subject'], $defs, $_map, $row['reverse'] );
//					echo "routes[{$row['name']}] = new Zend_Controller_Router_Route_Regex ( {$row['subject']}, $_defs, $_map, {$row['reverse']} );<br/>";
					break;
				}
		    if ( $route ) {
        		$ids[] = $row['id'];
        		$routes[$row['name']] = $route;
        	}
		}
		
        unset($rows);		
		return array ($ids, $routes );
	}
	
	private function _toTextArray($data) {
		$vars = array ();
		$pairs = explode ( "\n", $data );
		foreach ( $pairs as $i => $pair ) {
			$items = explode ( ":", $pair );
			if (count ( $items ) == 2) {
				$vars [$items [0]] = trim ( $items [1] );
			}
		}
		return $vars;
	}

}